package com.navi.bean.sql;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;

import java.util.List;

import static com.navi.core.constant.SQLStatics.AND;
import static com.navi.core.constant.SQLStatics.OR;

public class SqlVo {
    /** SQL语句 */
    private final StringBuilder sql;

    /** 参数列表 */
    private List<Object> params;



    /**
     * 构造方法
     */
    public SqlVo() {
        sql = new StringBuilder();
    }

    /**
     * 构造方法
     * @param sql SQL语句
     */
    public SqlVo(final String sql) {
        this.sql = new StringBuilder(sql);
        //if (!sql.toUpperCase().contains(WHERE)) {
        //    appendSql(WHERE).appendSql("1 = 1");
        //}
    }


    /**
     * 获取SQL语句
     * @return SQL语句
     */
    public String getSql() {
        return sql.toString();
    }


    /**
     * 获取参数数组
     * @return 参数数组
     */
    public Object[] getParams() {
        if (CollectionUtils.isNotEmpty(params)) {
            return params.toArray();
        }
        return null;
    }


    /**
     * 拼接SQL语句
     * @param subSql 子SQL语句
     * @return SQL语句对象
     */
    public SqlVo appendSql(final String subSql) {
        sql.append(" ").append(subSql.trim());
        return this;
    }


    /**
     * 拼接SQL语句并增加参数
     * @param subSql 子SQL语句
     * @param params 参数数组
     * @return SQL语句对象
     */
    public SqlVo appendSqlAndAddParam(String subSql, final Object... params) {
        if (ArrayUtils.isNotEmpty(params)) {
            for (final Object param : params) {
                subSql = subSql.replaceFirst("\\?", "'" + param.toString() + "'");
            }
        }
        return this.appendSql(subSql);
    }


    /**
     * 拼接in所需的SQL语句
     * @param str 字符串，前台框架以#@#拼接的结果。
     * @return SQL语句
     */
    public static String jointInSql(final String str) {
        return jointInSql(str.split(","), true, true);
    }


    /**
     * 拼接AND语句
     * @return SQL语句对象
     */
    public SqlVo and() {
        return appendSql(AND);
    }


    /**
     * 拼接OR语句
     * @return SQL语句对象
     */
    public SqlVo or() {
        return appendSql(OR);
    }



    /**
     * 拼接in所需的SQL语句
     * @param idsArr ID数组
     * @param withBracket 是否包含前后的括号
     * @param withQuotation 是否为每个项增加引号
     * @return SQL语句
     */
    public static String jointInSql(final String[] idsArr, final boolean withBracket, final boolean withQuotation) {
        final StringBuilder sb = new StringBuilder();
        if (withBracket) {
            sb.append("(");
        }
        for (final String str : idsArr) {
            if (withQuotation) {
                sb.append("'");
            }
            sb.append(str);
            if (withQuotation) {
                sb.append("'");
            }
            sb.append(",");
        }
        sb.deleteCharAt(sb.length() - 1);
        if (withBracket) {
            sb.append(")");
        }
        return sb.toString();
    }

}
